#!/usr/bin/env python3
"""
诊断 Windows DLL 加载问题
"""
import os
import sys
import platform
import subprocess

def check_python_info():
    """检查 Python 环境信息"""
    print("🐍 Python 环境信息")
    print("=" * 50)
    print(f"Python 版本: {sys.version}")
    print(f"Python 架构: {platform.architecture()}")
    print(f"Python 位数: {64 if sys.maxsize > 2**32 else 32} 位")
    print(f"Python 路径: {sys.executable}")
    print(f"当前工作目录: {os.getcwd()}")

def check_pyd_file():
    """检查 pyd 文件信息"""
    print(f"\n🔍 检查 .pyd 文件")
    print("=" * 50)
    
    pyd_path = "my_package/c_module/my_c_string.pyd"
    
    if os.path.exists(pyd_path):
        stat = os.stat(pyd_path)
        print(f"✅ 文件存在: {pyd_path}")
        print(f"文件大小: {stat.st_size} 字节")
        print(f"修改时间: {stat.st_mtime}")
        
        # 尝试用 file 命令检查文件类型（如果可用）
        try:
            result = subprocess.run(['file', pyd_path], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"文件类型: {result.stdout.strip()}")
        except:
            pass
        
        return True
    else:
        print(f"❌ 文件不存在: {pyd_path}")
        return False

def check_dependencies():
    """检查依赖项"""
    print(f"\n📚 检查依赖项")
    print("=" * 50)
    
    # 检查是否有 dumpbin 工具
    try:
        result = subprocess.run(['dumpbin', '/dependents', 'my_package/c_module/my_c_string.pyd'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("📋 DLL 依赖项:")
            print(result.stdout)
        else:
            print("⚠️  无法运行 dumpbin，可能未安装 Visual Studio")
    except FileNotFoundError:
        print("⚠️  dumpbin 工具未找到")
    
    # 检查 Python DLL
    python_dll = f"python{sys.version_info.major}{sys.version_info.minor}.dll"
    python_dll_path = os.path.join(os.path.dirname(sys.executable), python_dll)
    
    print(f"\n🔍 Python DLL 检查:")
    print(f"期望路径: {python_dll_path}")
    print(f"存在: {'✅' if os.path.exists(python_dll_path) else '❌'}")

def test_import_detailed():
    """详细测试导入过程"""
    print(f"\n🧪 详细导入测试")
    print("=" * 50)
    
    # 测试模块路径
    print("Python 模块搜索路径:")
    for i, path in enumerate(sys.path):
        print(f"  {i}: {path}")
    
    # 测试导入步骤
    try:
        print(f"\n📦 测试导入 my_package...")
        import my_package
        print(f"✅ my_package 导入成功")
        print(f"my_package 路径: {my_package.__file__}")
        
        print(f"\n📦 测试导入 my_package.c_module...")
        import my_package.c_module
        print(f"✅ my_package.c_module 导入成功")
        print(f"c_module 路径: {my_package.c_module.__file__}")
        
        print(f"\n📦 测试导入 my_c_string...")
        import my_package.c_module.my_c_string
        print(f"✅ my_c_string 导入成功！")
        
        # 测试函数调用
        if hasattr(my_package.c_module.my_c_string, 'hello'):
            result = my_package.c_module.my_c_string.hello()
            print(f"✅ 函数调用成功: {result}")
        
    except ImportError as e:
        print(f"❌ 导入失败: {e}")
        
        # 更详细的错误信息
        import traceback
        print(f"\n📋 详细错误信息:")
        traceback.print_exc()
        
    except Exception as e:
        print(f"❌ 其他错误: {e}")
        import traceback
        traceback.print_exc()

def suggest_solutions():
    """建议解决方案"""
    print(f"\n💡 可能的解决方案")
    print("=" * 50)
    
    solutions = [
        "1. 重新编译确保架构匹配",
        "2. 检查 Visual C++ 运行时库",
        "3. 确保 Python 开发库正确链接",
        "4. 检查 CMake 配置",
        "5. 使用 Dependency Walker 分析 DLL 依赖",
    ]
    
    for solution in solutions:
        print(f"   {solution}")
    
    print(f"\n🔧 具体操作:")
    print("   - 重新安装: pip uninstall my-package && pip install -e . -v")
    print("   - 检查架构: python -c \"import platform; print(platform.architecture())\"")
    print("   - 强制重新编译: pip install -e . --force-reinstall -v")

def main():
    print("🔧 Windows DLL 加载问题诊断")
    print("分析 my_c_string.pyd 导入失败原因")
    print("=" * 70)
    
    check_python_info()
    pyd_exists = check_pyd_file()
    
    if pyd_exists:
        check_dependencies()
        test_import_detailed()
    
    suggest_solutions()
    
    print(f"\n" + "=" * 70)
    print(f"🎯 下一步建议:")
    print(f"   1. 如果是依赖问题，安装 Visual C++ Redistributable")
    print(f"   2. 如果是架构问题，重新编译")
    print(f"   3. 如果是链接问题，检查 CMakeLists.txt")
    print("=" * 70)

if __name__ == "__main__":
    main() 